import requests
from loguru import logger
import re
import ddddocr
import os
import time

curr_path = os.getcwd()

def get_code(Captha_file):
    ocr = ddddocr.DdddOcr(beta=True)  # 切换为第二套ocr模型
    image = open(Captha_file, "rb").read()
    result = ocr.classification(image)
    return result

def get_captcha(Captha_file, proxies):
    headers = {
        "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Pragma": "no-cache",
        "Referer": "https://www.yangming.com/VerifyYourID.aspx",
        "Sec-Fetch-Dest": "image",
        "Sec-Fetch-Mode": "no-cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
        "sec-ch-ua": "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\""
    }
    url = "https://www.yangming.com/e-service/schedule/CAPTCHA.ashx"
    try:
        res = requests.get(url, headers=headers, proxies=proxies)
        if res.status_code == 200:
            with open(Captha_file, 'wb')as f:
                f.write(res.content)
            logger.info(f"YML: 成功获取验证码图片")
        else:
            logger.error(f"获取图片异常: {res.status_code}")
    except Exception as e:
        logger.error(f"获取图片异常: {e}")
        return None

def get_verify(proxies):
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Pragma": "no-cache",
        "Referer": "https://www.yangming.com/e-service/schedule/P-to-PSearch.aspx",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
        "sec-ch-ua": "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\""
    }
    url = "https://www.yangming.com/VerifyYourID.aspx"
    retry_count = 0
    while retry_count < 3:
        res = requests.get(url, headers=headers, proxies=proxies)
        if res.status_code == 200:
            __VIEWSTATE = re.findall('id="__VIEWSTATE" value="(.*?)"', res.text)[0]
            __VIEWSTATEGENERATOR = re.findall('id="__VIEWSTATEGENERATOR" value="(.*?)"', res.text)[0]
            __VIEWSTATEENCRYPTED = re.findall('id="__VIEWSTATEENCRYPTED" value="(.*?)"', res.text)[0] if re.findall('id="__VIEWSTATEENCRYPTED" value="(.*?)"', res.text) else ''
            __EVENTVALIDATION = re.findall('id="__EVENTVALIDATION" value="(.*?)"', res.text)[0]
            Captha_file = "CAPTCHA.png"
            Captha_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), Captha_file)
            get_captcha(Captha_file, proxies)
            time.sleep(0.5)
            txtVcode = get_code(Captha_file)
            res = post_verify(__VIEWSTATE, __VIEWSTATEGENERATOR, __VIEWSTATEENCRYPTED, __EVENTVALIDATION, txtVcode, proxies)
            if res == 1:
                logger.success(f"yml成功通过验证码")
                return 1
            elif res == 0:
                logger.error(f"yml通过验证码失败")
                retry_count += 1
        else:
            logger.error(f"请求yml验证码异常: {res.status_code}")
            retry_count += 1
            continue
    if retry_count == 3:
        return None

def post_verify(__VIEWSTATE, __VIEWSTATEGENERATOR, __VIEWSTATEENCRYPTED, __EVENTVALIDATION, txtVcode, proxies):
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Type": "application/x-www-form-urlencoded",
        "Origin": "https://www.yangming.com",
        "Pragma": "no-cache",
        "Referer": "https://www.yangming.com/VerifyYourID.aspx",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
        "sec-ch-ua": "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\""
    }
    url = "https://www.yangming.com/VerifyYourID.aspx"
    data = {
        "__EVENTTARGET": "btnVerify",
        "__EVENTARGUMENT": "",
        "__VIEWSTATE": __VIEWSTATE,
        "__VIEWSTATEGENERATOR": __VIEWSTATEGENERATOR,
        "__VIEWSTATEENCRYPTED": __VIEWSTATEENCRYPTED,
        "__EVENTVALIDATION": __EVENTVALIDATION,
        "txtVcode": str(txtVcode)
    }
    res = requests.post(url, headers=headers, data=data, proxies=proxies, allow_redirects=False)
    if res.status_code == 302:
        return 1
    else:
        return 0

# get_verify()